package com.wteam.clightmini.controller;


import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wteam.clightmini.pojo.Admin;
import com.wteam.clightmini.service.AdminService;
import com.wteam.system.common.ResultMessage;
import com.wteam.system.utils.JwtUtils;
import io.swagger.annotations.Api;
import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 许则丕
 * @since 2022-07-11
 */
@RestController
@RequestMapping("/admin")
@Api(tags = "系统：登录")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    JwtUtils jwtUtils;


    @PostMapping("/login")
    public ResultMessage login(@Validated @RequestBody Admin admin1, HttpServletResponse response){
        Admin admin = adminService.getOne(new QueryWrapper<Admin>().eq("name", admin1.getName()));
        ResultMessage resultMessage = new ResultMessage();
        Assert.notNull(admin,"用户不存在");//断言拦截
        try {
            //判断账号密码是否错误
            if(!admin.getPassword().equals(admin1.getPassword())){
                //密码不同则抛出异常
                resultMessage.setMessage("密码不正确");
                resultMessage.setStatus(HttpStatus.HTTP_BAD_REQUEST);
                return resultMessage;
            }
            Map<String, Object> map = new HashMap<>();
                    map.put("id", admin.getId());
                    map.put("name", admin.getName());
                    map.put("password", admin.getPassword());
                    resultMessage.setResultParam(map);
            return resultMessage;
        }catch (IllegalArgumentException e) {
            e.printStackTrace();
            resultMessage.setMessage("参数不正确");
            resultMessage.setStatus(HttpStatus.HTTP_BAD_REQUEST);
        }
        catch (Exception e) {
            e.printStackTrace();
            resultMessage.setMessage("登录失败");
            resultMessage.setStatus(HttpStatus.HTTP_BAD_REQUEST);
        }
        return resultMessage;
    }

}
